package com.ybkj.daijia.server.event.listener.zhuanxian;

import com.ybkj.daijia.serverUtils.HttpClientUtil;
import com.ybkj.daijia.PushDataV4;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.api.gexin.GeTuiEmployV4;
import com.ybkj.daijia.api.jpush.JiGuangEmployV4;
import com.ybkj.daijia.server.event.model.zhuanxian.ZhuanxianOrderCreateEvent;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.DriverGrade;
import com.ybkj.daijia.server.model.DriverRefuseRecord;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.DriverGradeService;
import com.ybkj.daijia.server.service.DriverRefuseRecordService;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.ZhuanxianService;
import com.ybkj.daijia.server.websocket.WebSocketSend;
import com.ybkj.daijia.server.zhuanxian.Car;
import com.ybkj.daijia.server.zhuanxian.Order;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

@Component
public class ZhuanxianOrderCreateEventListener implements
    ApplicationListener<ZhuanxianOrderCreateEvent> {

    private static final Logger logger = LoggerFactory
        .getLogger(ZhuanxianOrderCreateEventListener.class);

    @Autowired
    private ZhuanxianService zhuanxianService;

    @Autowired
    private DriverService driverService;

    @Autowired
    private DriverGradeService driverGradeService;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private DriverRefuseRecordService driverRefuseRecordService;

    @Autowired
    private SettingUtils settingUtils;

    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;


    @Override
    @Async
    public void onApplicationEvent(ZhuanxianOrderCreateEvent event) {
        Long orderId = (Long) event.getSource();

        Order order = zhuanxianService.findOne(orderId);

        logger.debug("ZhuanxianOrderCreateEvent event:{}", order.getOrderNo());

        Setting setting = settingUtils.get();

        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type", "zhuanxianNewOrders_company");
            Company mainCompany = companyService.getMain();
            WebSocketSend.boardcastToCompany(jsonObject, order.getCompanyId(), mainCompany.getId());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        if (!order.isYuyue()) {

            Long lineId = order.getLineId();
            //推送数据到浏览器
            if (order.getStatus().equals(Order.ORDER_STATUS_NEW)) {

                List<Car> cars = zhuanxianService.findCarByLine(lineId);
                List<Long> carIds = new ArrayList<Long>();
                if (!CollectionUtils.isEmpty(cars)) {
                    for (Car car : cars) {
                        carIds.add(car.getId());
                    }

                    List<Driver> drivers = driverService.findByZhuanxianCars(carIds);
                    List<Driver> newDrivers = new ArrayList<Driver>();
                    if (!CollectionUtils.isEmpty(drivers)) {
                        for (Driver driver : drivers) {
                            if (driver.getDriverJobType()
                                .contains(Driver.DriverJobType.zhuanxian.toString())) {
                                if (!driver.isWorkCar() && !driver.getIsFreeze() && (
                                    null == driver.getJobStatus() || driver.getJobStatus()
                                        .equals(Driver.DRIVER_JOBSTATUS_ZHUANXIAN))) {
                                    //拒单记录
                                    Long refusedNum = driverRefuseRecordService
                                        .countByOrderIdEmployIdAndOrderType(orderId, driver.getId(),
                                            DriverRefuseRecord.OrderType.zhuanxian.toString());
                                    if (refusedNum == 0) {
                                        Car car = zhuanxianService
                                            .findCar(driver.getZhuanxianCarId());
                                        if (null != car) {
                                            List<Order> nowOrders = zhuanxianService
                                                .findActivedOrdersByDriver(driver.getId());
                                            if (!CollectionUtils.isEmpty(nowOrders)) {
                                                if (Order.TYPE_PINCHE
                                                    .equals(order.getOrderType())) {
                                                    if (driver.getStatus()
                                                        != Driver.DRIVER_OFFLINE) {
                                                        long seats = 0;
                                                        boolean flag = false;
                                                        boolean haschufa = false;
                                                        for (Order nowOrder : nowOrders) {
                                                            if (!Order.TYPE_PINCHE
                                                                .equals(nowOrder.getOrderType())) {
                                                                flag = true;
                                                                break;
                                                            }
                                                            if (!nowOrder.isYuyue()) {
                                                                seats += nowOrder.getPeopleNumber();
                                                            }
                                                            if (nowOrder.getStatus().equals(
                                                                Order.ORDER_STATUS_ZHIXING)) {
                                                                haschufa = true;
                                                            }
                                                        }
                                                        if (!flag) {
                                                            driver.setSeatsNow(seats);
                                                            if (seats + order.getPeopleNumber()
                                                                <= car.getRidepeopleNumber()) {
                                                                if (!haschufa) {
                                                                    newDrivers.add(driver);
                                                                }
                                                            }
                                                        }
                                                    }
                                                } else if (Order.TYPE_BAOCHE
                                                    .equals(order.getOrderType())) {

                                                } else if (Order.TYPE_JIHUO
                                                    .equals(order.getOrderType())) {
                                                    if (driver.getStatus()
                                                        != Driver.DRIVER_OFFLINE) {
                                                        boolean hasZhixing = false;
                                                        boolean flag = false;
                                                        for (Order nowOrder : nowOrders) {
                                                            if (Order.ORDER_STATUS_ZHIXING
                                                                .equals(nowOrder.getStatus())) {
                                                                hasZhixing = true;
                                                                break;
                                                            }
                                                            if (!Order.TYPE_JIHUO
                                                                .equals(nowOrder.getOrderType())) {
                                                                flag = true;
                                                                break;
                                                            }
                                                        }
                                                        if (!hasZhixing && !flag) {
                                                            newDrivers.add(driver);
                                                        }
                                                    }
                                                }
                                            } else {
                                                if (Order.TYPE_PINCHE
                                                    .equals(order.getOrderType())) {
                                                    if (driver.getStatus()
                                                        != Driver.DRIVER_OFFLINE) {
                                                        long seats = 0;
                                                        driver.setSeatsNow(seats);
                                                        if (seats + order.getPeopleNumber() <= car
                                                            .getRidepeopleNumber()) {
                                                            newDrivers.add(driver);
                                                        }
                                                    }
                                                } else {
                                                    if (driver.getStatus()
                                                        == Driver.DRIVER_ONLINE) {
                                                        newDrivers.add(driver);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    if (!CollectionUtils.isEmpty(newDrivers)) {
                        for (Driver driver : newDrivers) {
//							1拼车（不能超出座位，已有座位优先） 包车（只能一单） 寄货（出发后不能派）
//							2等级
//							3距离

                            if (null != driver.getGradeId()) {
                                DriverGrade driverGrade = driverGradeService
                                    .findOne(driver.getGradeId());
                                if (null != driverGrade) {
                                    driver.setGrade(driverGrade.getGrade());
                                }
                            }
                        }

                        Collections.sort(newDrivers, new Comparator<Driver>() {
                            public int compare(Driver arg0, Driver arg1) {
                                return arg1.getGrade().compareTo(arg0.getGrade());
                            }
                        });

                        if (Order.TYPE_PINCHE.equals(order.getOrderType())) {
                            Collections.sort(newDrivers, new Comparator<Driver>() {
                                public int compare(Driver arg0, Driver arg1) {
                                    return arg1.getSeatsNow().compareTo(arg0.getSeatsNow());
                                }
                            });

                            String yuyueCity = HttpClientUtil
                                .getCityByLngAndLat(order.getStartLng(), order.getStartLat());
                            List<Driver> pincheDrivers = new ArrayList<Driver>();
                            for (Driver driver : newDrivers) {
                                if (!driver.getStatus().equals(Driver.DRIVER_OFFLINE)) {
                                    String driverCity = HttpClientUtil
                                        .getCityByLngAndLat(driver.getLongitude(),
                                            driver.getLatitude());
                                    if (driverCity.equals(yuyueCity)) {
                                        pincheDrivers.add(driver);
                                    }
                                }
                            }

                            newDrivers = new ArrayList<Driver>();
                            newDrivers.addAll(pincheDrivers);
                        }

                        if (!CollectionUtils.isEmpty(newDrivers)) {
                            if (setting.isAutoPaidanZhuanxian()) {
                                //派单
                                zhuanxianService.autoPaidan(newDrivers.get(0), order);
                            } else if (setting.isAllowRushOrderZhuanxian()) {
                                for (Driver newDriver : newDrivers) {
                                    pushNewOrder(order, newDriver, setting);
                                }
                            }
                        }

                    }


                }
            }
        }

    }

//    private void start(Order newOrder,Setting setting) {
//      
//    }

    private void pushNewOrder(Order newOrder, Driver rushDriver, Setting setting) {
        try {

            PushDataV4 pushDataV4 = new PushDataV4();
            pushDataV4.setCode("0X02");
            pushDataV4.setData(newOrder.getId());
            pushDataV4.setType("0X04");
            pushDataV4.setSound("beep_2");
            Map<String, String> extra = new HashMap<String, String>();
            extra.put("content", "又有新工单可以抢啦");
            pushDataV4.setExtra(extra);

            boolean getuiOnline = false;
            if (StringUtils.isNotBlank(rushDriver.getUserID())) {
                getuiOnline = GeTuiEmployV4
                    .getClientOnline(rushDriver.getUserID(), settingUtils.get());
            }

            if (getuiOnline) {
                GeTuiEmployV4.push(rushDriver, pushDataV4, setting);
            } else {
                if (StringUtils.isNotBlank(rushDriver.getRegistrationId())) {
                    JiGuangEmployV4.push(rushDriver, pushDataV4, setting);
                }
            }

        } catch (IOException e) {
            logger.debug("push error : " + e.getMessage());
        }
    }


}
